<?php
/**
 * Created by PhpStorm.
 * User: Mysic
 * Date: 2020/12/28
 * Time: 9:24
 */

namespace app\common\mysic\profitShare\procedures;


use app\admin\model\BaseSetting;
use app\common\exception\BaseException;
use app\common\model\Agent;
use app\common\model\divide\Receive;
use app\common\model\divide\ReceivesLog;
use app\common\model\divide\Service;
use app\common\model\divide\Store;
use app\common\model\divide\System;
use app\common\model\Order;
use app\common\model\User;
use app\common\model\dealer\User as Dealer;
use app\common\model\Wxsetting;
use app\common\model\Wxapp;
use app\common\model\VipCardOrder;
use app\common\mysic\exceptions\EntityErrorException;
use app\common\mysic\MysicBase;
use think\Collection;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use utils\Services;

class DbData extends MysicBase
{
    protected $userOrderModel;
    protected $wxSettingModel;
    protected $userModel;
    protected $agentModel;
    protected $wxAppModel;
    protected $receiveModel;
    protected $receivesLogModel;
    protected $dealerModel;
    protected $vipCardOrderModel;
    protected $systemProfitModel;
    protected $serviceProfitModel;
    protected $storeProfitModel;

    protected $userOrderEntity;
    protected $wxSettingEntity;
    protected $systemProfitOrderEntity;
    protected $serviceProfitOrderEntities;
    protected $storeProfitOrderEntity;
    protected $dealerEntity;
    protected $userEntity;
    protected $userEntities;
    protected $agentEntity;
    protected $wxAppEntity;
    protected $vipCardOrderEntity;
    protected $receivesEntities = [];
    protected $receivesLogEntities = [];
    protected $agentArray = [];
    protected $receiveOrderEntities;
    protected $wxApiConfigEntity = [];
    protected $systemSettingArray = [];

    public function __construct()
    {
        parent::__construct();
        $this->userOrderModel = new Order();
        $this->wxSettingModel = new Wxsetting();
        $this->userModel = new User();
        $this->agentModel = new Agent();
        $this->wxAppModel = new Wxapp();
        $this->receiveModel = new Receive();
        $this->receivesLogModel = new ReceivesLog();
        $this->dealerModel = new Dealer();
        $this->vipCardOrderModel = new VipCardOrder();
        $this->systemProfitModel = new System();
        $this->serviceProfitModel = new Service();
        $this->storeProfitModel = new Store();

    }

    public function initUserOrderEntity($paidOrderNo): DbData
    {
        $this->userOrderEntity = $this->userOrderModel->where('order_no', $paidOrderNo)->find();
        if(!$this->userOrderEntity) {
            throw new EntityErrorException('用户订单实体不存在. order_no:' . $paidOrderNo);
        }
        $this->log->info(json_encode($this->userOrderEntity->toArray()) ?? '', '初始化当前支付订单的信息');
        return $this;
    }

    public function getUserOrderEntity(): Order
    {
        return $this->userOrderEntity;
    }

    public function initVipCardOrder($orderId): DbData
    {
        $this->vipCardOrderEntity = $this->vipCardOrderModel->where('order_id', $orderId)->find();
        if(!$this->vipCardOrderEntity) {
            throw new EntityErrorException('储值卡订单实体不存在. order id:' . $orderId);
        }
        $this->log->info(json_encode($this->vipCardOrderEntity->toArray() ?? '', JSON_UNESCAPED_UNICODE), '初始化储值卡订单信息');
        return $this;
    }

    public function getVipCardOrderEntity()
    {
        return $this->vipCardOrderEntity;
    }

    public function initReceivesEntitiesByWxAppIdPeriodsNum($wxAppId, $periodsNum): DbData
    {
        $this->log->info(['wxapp_id' => $wxAppId, 'periods_num' => $periodsNum], '初始化分红队列实体 - 初始化参数');
        $receivesEntities = $this->receiveModel->where('wxapp_id', $wxAppId)
            ->where('type', 0)
            ->where('periods_num', $periodsNum)
            ->whereTime('finish_time', '>', time())
            ->field('receives_id,type,order_no, times,balance,wxapp_id,payment,periods_num,user_id,account,top_limit,transaction_id,is_large')
            ->order('create_time desc')
            ->select();
        $this->receivesEntities = $receivesEntities->all();
        $this->log->info(count($this->receivesEntities), '初始化分红队列实体 - 分红队列实体数量');
        return $this;
    }

    public function getReceivesEntities(): array
    {
        return $this->receivesEntities;
    }

    public function initWxSettingEntity($wxAppId): DbData
    {
        $this->wxSettingEntity = $this->wxSettingModel->where('wxapp_id', $wxAppId)->find();
        if(!$this->wxSettingEntity) {
            throw new EntityErrorException('商户小程序分账设置实体不存在. wxapp id:' . $wxAppId);
        }
        $this->log->info(json_encode($this->wxSettingEntity->toArray() ?? [], JSON_UNESCAPED_UNICODE), '初始化商户分红设置');
        return $this;
    }

    public function getWxSettingEntity()
    {
        return $this->wxSettingEntity;
    }

    public function initUserEntity($userId): DbData
    {
        $this->userEntity = $this->userModel->where('user_id', $userId)->find();
        if(!$this->userEntity) {
            throw new EntityErrorException('用户信息实体不存在. user id:' . $userId);
        }
        $this->log->info(json_encode($this->userEntity->toArray(), JSON_UNESCAPED_UNICODE), '初始化用户信息');
        return $this;
    }

    public function getUserEntity(): User
    {
        return $this->userEntity;
    }

    public function initUserEntitiesByReceivesEntities(): DbData
    {
        $this->log->info('根据分红队列实体所属用户ID获取用户信息列表');
        $userIds = [];
        foreach($this->receivesEntities as $receiveEntity) {
            $userIds[] = $receiveEntity->user_id;
        }
        $userIds = array_unique($userIds);
        $userEntities = $this->userModel->whereIn('user_id', $userIds)->select();
        $userEntities = $userEntities->all();
        foreach($userEntities as $userEntity) {
            $this->userEntities[$userEntity->user_id] = $userEntity;
        }
        return $this;
    }

    public function getUserEntities()
    {
        return $this->userEntities;
    }

    public function initAgentEntity($agentId): DbData
    {
        $this->agentEntity = $this->agentModel->where('agent_id', $agentId)->find();
        if(!$this->agentEntity) {
            $this->agentEntity['service_charge'] = 0.02;
            $this->agentEntity = Collection::make($this->agentEntity);
        }
        $this->log->info(json_encode($this->agentEntity ? $this->agentEntity->toArray() : [], JSON_UNESCAPED_UNICODE), '初始化代理商信息');
        return $this;
    }

    public function getAgentEntity()
    {
        return $this->agentEntity;
    }

    public function initWxAppEntity($wxAppId):DbData
    {
        $this->wxAppEntity = $this->wxAppModel->where('wxapp_id', $wxAppId)->find();
        if(!$this->wxAppEntity) {
            throw new EntityErrorException('商户小程序实体不存在. wxapp id:' . $wxAppId);
        }
        $this->log->info(json_encode($this->wxAppEntity->toArray(), JSON_UNESCAPED_UNICODE), '初始化微信小程序信息');
        return $this;
    }

    public function getWxAppEntity()
    {
        return $this->wxAppEntity;
    }

    public function initAgentsArray($agentId):DbData
    {
        $agentArray = Db::name('agent')->where(['is_recycle' => 0, 'status' => 1, 'is_delete' => 0])->order('agent_id desc')->select();
        $agentArray = $agentArray->toArray();
        if(!empty($agentArray)) {
            $tree = Services::instance();
            $tree->init($agentArray, 'recommend_id');
            $withSelf = true;
            if (3 == $this->agentEntity->type) {
                $withSelf = false;
            }
            $this->agentArray = $tree->getParents($agentId, $withSelf);
        }
        $this->log->info(json_encode($this->agentArray, JSON_UNESCAPED_UNICODE), '初始代理商列表信息');
        return $this;
    }

    public function getAgentArray(): array
    {
        return $this->agentArray;
    }

    public function initDealerEntity($userId):DbData
    {
        try {
            $this->dealerEntity = $this->dealerModel->where('user_id', $userId)->find();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            $this->dealerEntity = null;
        }
        if(!$this->dealerEntity) {
            throw new EntityErrorException('分销商信息实体不存在. user id:' . $userId);
        }
        $this->log->info(json_encode($this->dealerEntity->toArray(), JSON_UNESCAPED_UNICODE), '初始化用户分销身份信息');
        return $this;
    }

    public function getDealerEntity():Dealer
    {
        return $this->dealerEntity;
    }

    public function initReceivesEntitiesByReceivesOrderNos(array $orderNos): DbData
    {
        $this->log->info('根据分红订单号初始化分红队列实体列表');
        $receivesEntities = $this->receiveModel->whereIn('order_no', $orderNos)->select();
        $this->receivesEntities = $receivesEntities->all();
        return $this;
    }

    public function initWxApiConfigEntity($wxAppId):DbData
    {
        try {
            $this->wxApiConfigEntity = Wxapp::getWxappRedis($wxAppId);
        } catch (BaseException | DbException | Exception $e) {
            $this->log->error(exceptionLogFormat($e), '获取微信接口设置实体抛出异常');
            $this->wxApiConfigEntity = null;
        }
        if(!$this->wxApiConfigEntity) {
            throw new EntityErrorException('微信接口设置实体不存在. wxapp id:' . $wxAppId);
        }
        $this->log->info(json_encode($this->wxApiConfigEntity,JSON_UNESCAPED_UNICODE), '初始化微信接口配置');
        return $this;
    }

    public function getWxApiConfigEntity(): array
    {
        return $this->wxApiConfigEntity;
    }

    public function initSystemSetting($wxAppId): DbData
    {
        if(!$wxAppEntity = $this->getWxAppEntity()){
            try {
                $this->initWxAppEntity($wxAppId);
            } catch (EntityErrorException $e) {
                throw $e;
            }
        }
        if(!$wxAppEntity) {
            $wxAppEntity = $this->getWxAppEntity();
        }

        $this->log->info($wxAppEntity->service_type, '商户小程序配置');
        if(1 == $wxAppEntity->service_type) {
            $data = BaseSetting::detail('wechat');
        } elseif(2 == $wxAppEntity->service_type) {

            $data = BaseSetting::detail('wechat_wgk');
        } else {
            throw new EntityErrorException('商户小程序service_type值错误. service_type: ' . $wxAppEntity->service_type);
        }
        $this->systemSettingArray = $data->toArray()['values'];
        $this->log->info($this->systemSettingArray, '系统平台配置');
        return $this;
    }

    public function getSystemSetting(): array
    {
        return $this->systemSettingArray;
    }

    public function initSystemProfitOrderEntity($paidOrderNo)
    {
        $this->systemProfitOrderEntity = $this->systemProfitModel->where('order_no', $paidOrderNo)->find();
        if(!$this->systemProfitOrderEntity) {
            throw new EntityErrorException('平台分账订单实体不存在. order no:' . $paidOrderNo);
        }
        $this->log->info(json_encode($this->systemProfitOrderEntity->toArray() ?? [], JSON_UNESCAPED_UNICODE), '初始化平台订单分账记录');
    }

    public function getSystemProfitOrderEntity()
    {
        return $this->systemProfitOrderEntity;
    }

    public function initServiceProfitOrderEntities($paidOrderNo)
    {
        $this->serviceProfitOrderEntities = $this->serviceProfitModel->where('order_no', $paidOrderNo)->select();
        if(!$this->serviceProfitOrderEntities) {
            throw new EntityErrorException('服务商分账订单实体不存在. order no:' . $paidOrderNo);
        }
        $this->serviceProfitOrderEntities = $this->serviceProfitOrderEntities->all();
    }

    public function getServiceProfitOrderEntities()
    {
        return $this->serviceProfitOrderEntities;
    }

    public function initStoreProfitOrderEntity($paidOrderNo)
    {
        $this->storeProfitOrderEntity = $this->storeProfitModel->where('order_no', $paidOrderNo)->find();
        if(!$this->storeProfitOrderEntity) {
            throw new EntityErrorException('商户分账订单实体不存在. order no:' . $paidOrderNo);
        }
        $this->log->info(json_encode($this->storeProfitOrderEntity->toArray() ?? [], JSON_UNESCAPED_UNICODE), '初始化商户分账订单实体');
    }

    public function getStoreProfitOrderEntity()
    {
        return $this->storeProfitOrderEntity;
    }

    public function initReceivesLogEntitiesByPaidOrderNo($paidOrderNo): DbData
    {
        $this->log->info('根据支付订单的订单号，初始化分红流水列表');
        $receivesLogEntities = $this->receivesLogModel->where('order_no', $paidOrderNo)->select();
        $receivesLogEntities = $receivesLogEntities->all();
        foreach($receivesLogEntities as $receivesLogEntity) {
            $this->receivesLogEntities[$receivesLogEntity->receives_order_no] = $receivesLogEntity;
        }
        return $this;
    }

    public function initReceivesLogEntitiesByReceivesOrderNo()
    {

    }

    public function getReceivesLogEntities(): array
    {
        return $this->receivesLogEntities;
    }

    public function initReceiveOrderEntities($orderNos): DbData
    {
        $this->log->info('初始化分红队列的订单列表');
        $receiveOrderEntities = $this->userOrderModel->whereIn('order_no', $orderNos)->select();
        $receiveOrderEntities = $receiveOrderEntities->all();
        foreach($receiveOrderEntities as $receiveOrderEntity) {
            $this->receiveOrderEntities[$receiveOrderEntity->order_no] = $receiveOrderEntity;
        }
        return $this;
    }

    public function getReceiveOrderEntities()
    {
        return $this->receiveOrderEntities;
    }

    public function getReceiveOrderEntityByOrderNo($orderNo):Order
    {
        return $this->receiveOrderEntities[$orderNo];
    }

}